package com.maserb.monitor.service.jwOur.impl;

import com.maserb.monitor.entity.jwOur.JwMessageEntity;
import com.maserb.monitor.repository.jwOur.JwMessageRepository;
import com.maserb.monitor.service.base.impl.JpaSpecificationServiceImpl;
import com.maserb.monitor.service.jwOur.JwMessageService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class JwMessageServiceImpl extends JpaSpecificationServiceImpl<JwMessageRepository,
        JwMessageRepository, JwMessageEntity, String>
        implements JwMessageService {
    @Override
    public List<JwMessageEntity> findByIsReleaseAndIsDel(String isRelease, String isDel) {
        return this.repository.findByIsReleaseAndIsDel(isRelease,isDel);
    }

    @Override
    public Page<JwMessageEntity> findAll(Pageable pageable, String isRelease ,String description) {

        return this.findAll(new Specification<JwMessageEntity>() {
            @Override
            public Predicate toPredicate(Root<JwMessageEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<String> pathIsRelease = root.get("isRelease");
                Path<String> pathDescription = root.get("description");
                Path<String> pathIsDel = root.get("isDel");
                String isDel = "0";

                ArrayList<Predicate> list = new ArrayList<Predicate>();
                if (!StringUtils.isEmptyOrWhitespace(isRelease)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.equal(pathIsRelease,isRelease)));
                }
                if (!StringUtils.isEmptyOrWhitespace(isRelease)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.like(pathDescription,"%"+description+"%")));
                }
                list.add(criteriaBuilder.and(criteriaBuilder.equal(pathIsDel, isDel)));

                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        }, pageable);
    }

    @Override
    public void doRelease(String id) {
        JwMessageEntity entity = this.findOne(id);
        entity.setIsRelease("1");
        this.save(entity);
    }

    @Override
    public void doNoRelease(String id) {
        JwMessageEntity entity = this.findOne(id);
        entity.setIsRelease("0");
        this.save(entity);
    }
}